package com.ltu.timkor6.gamesite.games.missingbits.server;

import java.util.Random;

import com.ltu.timkor6.gamesite.games.missingbits.shared.Question;

public class CreateQuestion
{
	private final char MATH_ADDITION = '+';
	private final char MATH_SUBTRACTION = '-';
	private final char MATH_MULTIPLICATION = '*';
	private final char MATH_DIVISION = '/';
	
	private Question question;
	
	public CreateQuestion(Question question)
	{
		this.question = question;
		
		char sign = randomSign();
		question.setSign(sign);
		
		switch(sign)
		{
			case '/':
				calcDivision(sign);
				break;
			default:
				calcNormal(sign);
				break;
		}
	}
	
	public Question getQuestion()
	{
		return this.question;
	}
	
	private void calcNormal(char sign)
	{
		int first = randomNumber(10);
		int second = randomNumber(10);
		int result = calculate(first, second, sign);
		
		question.setFirst(first);
		question.setSecond(second);
		question.setResult(result);
	}
	
	private void calcDivision(char sign)
	{
		int second = randomNumber(10);
		int result = randomNumber(10);
		
		while(second == 0)
		{
			second = randomNumber(10);
		}
	
		int first = calculate(result, second, '*');
		
		question.setFirst(first);
		question.setSecond(second);
		question.setResult(result);
	}
	
	/**
	 * Generates a random number between 0 and 'number'-1.
	 */
	private int randomNumber(int number)
	{
		Random generator = new Random();
		
		return generator.nextInt(number);
	}
	
	private char randomSign()
	{
		int number = randomNumber(4);
		switch(number)
		{
			case 1:
				return this.MATH_SUBTRACTION;
			case 2:
				return this.MATH_MULTIPLICATION;
			case 3:
				return this.MATH_DIVISION;
			default:
				return this.MATH_ADDITION;
		}
	}
	
	private int calculate(int first, int second, char math)
	{
		int result = 0;
		switch(math)
		{
			case '+':
				return first + second;
			case '-':
				return first - second;
			case '*':
				return first * second;
			case '/':
				return first / second;
		}
		return result;
	}
}
